<?php

namespace app\controller\api;

use think\Controller;
use think\facade\Config;

class BaseController extends Controller
{
    protected function initialize()
    {
        parent::initialize();
        
        // 设置跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');
        
        // 处理 OPTIONS 请求
        if (request()->isOptions()) {
            exit();
        }
        
        // 设置时区
        date_default_timezone_set(Config::get('app.default_timezone', 'Asia/Shanghai'));
        
        // 设置语言
        \think\facade\Lang::setLangSet(Config::get('app.default_lang', 'zh-cn'));
        
        // 设置默认返回格式
        $this->responseType = 'json';
    }
    
    /**
     * 返回成功信息
     */
    protected function success($msg = '', $data = null, $code = 0)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
    
    /**
     * 返回错误信息
     */
    protected function error($msg = '', $data = null, $code = 1)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
} 